<template>
  <div>
    <Title :title="title"></Title>
    <div ref="right1" style="height: 150px;"></div>
  </div>
</template>

<script setup>
import Title from './Title.vue';
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { Column } from '@antv/g2plot';
import { get } from '@/utils/request';

const right1 = ref(null);
const title = ref('实时湿度-时间柱状图');
const currentHumidity = ref([]);
const columnPlot = ref(null); // 更名为columnPlot更符合实际图表类型
let refreshTimer = null;
let isFirstLoad = true;

// 时间颜色配置（使用渐变色）
const timeColors = [
  '#3b89ff', // 蓝色
  '#4ccaa1', // 青绿色
  '#ffc86b', // 黄色
  '#ff7a45', // 橙色
  '#a07ad9', // 紫色
  '#f56c6c', // 红色
];

// 获取当前时间字符串（格式：HH:mm:ss）
const getCurrentTime = () => {
  const now = new Date();
  return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
};

// 生成时间点数组（最近6个时间点）
const generateTimePoints = (baseTime = new Date()) => {
  const timePoints = [];
  for (let i = 5; i >= 0; i--) {
    const time = new Date(baseTime - i * 60000); // 前i分钟
    timePoints.push(`${time.getHours().toString().padStart(2, '0')}:${time.getMinutes().toString().padStart(2, '0')}`);
  }
  return timePoints;
};

// 处理数据为柱状图格式（时间为x轴）
const processData = (currentData, timePoints) => {
  return currentData.map((item, index) => ({
    time: timePoints[index],
    value: item.value,
    timeColor: timeColors[index % timeColors.length], // 循环使用颜色
  }));
};

// 生成模拟当前湿度数据（基于时间）
const generateMockCurrentData = () => {
  const baseValue = 55 + Math.random() * 10; // 基础湿度值
  return generateTimePoints().map((time, index) => ({
    time,
    value: parseFloat((baseValue + (Math.random() - 0.5) * 5).toFixed(1)), 
  }));
};

// 获取当前湿度数据（基于时间）
const fetchCurrentHumidity = async () => {
  try {
    const res = await get('/api/environment/humidity-time');
    if (res.data && Array.isArray(res.data) && res.data.length > 0) {
      return res.data.map(item => ({
        time: item.time, // 假设接口返回时间字段
        value: parseFloat(item.value.toFixed(1)),
      }));
    } else {
      return generateMockCurrentData();
    }
  } catch (error) {
    console.error('获取湿度-时间数据失败', error);
    return generateMockCurrentData();
  }
};

// 初始化图表
const initChart = () => {
  if (!right1.value) return;
  
  if (columnPlot.value) {
    columnPlot.value.destroy();
  }

  const timePoints = generateTimePoints();
  const processedData = processData(currentHumidity.value, timePoints);

  columnPlot.value = new Column(right1.value, {
    data: processedData,
    xField: 'time',
    yField: 'value',
    color: 'timeColor', // 使用时间颜色
    columnWidthRatio: 0.6, // 柱子宽度比例
    label: {
      visible: true,
      style: {
        fill: 'white',
        fontSize: 8,
      },
    },
    xAxis: {
      label: {
        style: {
          fill: 'white',
          fontSize: 8,
          rotate: 45, // 旋转标签避免重叠
        },
      },
      title: {
        text: '时间',
        style: {
          fill: 'white',
        },
      },
    },
    yAxis: {
      label: {
        style: {
          fill: 'white',
        },
      },
      title: {
        text: '湿度(%)',
        style: {
          fill: 'white',
        },
      },
    },
    theme: {
      plot: {
        backgroundColor: 'transparent',
      },
      axis: {
        line: {
          style: {
            stroke: 'rgba(255, 255, 255, 0.1)',
          },
        },
        tick: {
          line: {
            style: {
              stroke: 'rgba(255, 255, 255, 0.1)',
            },
          },
        },
      },
    },
  });

  columnPlot.value.render();
};

// 定时刷新当前湿度数据（1分钟刷新一次）
const startRefresh = async () => {
  try {
    const data = await fetchCurrentHumidity();
    currentHumidity.value = data;
    initChart();
    isFirstLoad = false;
    
    // 60000毫秒 = 60秒 = 1分钟
    refreshTimer = setInterval(async () => {
      const newData = await fetchCurrentHumidity();
      currentHumidity.value = newData;
      initChart();
    }, 60000);
  } catch (error) {
    console.error('初始化数据失败', error);
  }
};

// 停止刷新
const stopRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
    refreshTimer = null;
  }
};

onMounted(() => {
  startRefresh();
});

onUnmounted(() => {
  stopRefresh();
  if (columnPlot.value) {
    columnPlot.value.destroy();
  }
});

watch(currentHumidity, () => {
  if (!isFirstLoad && currentHumidity.value.length) {
    initChart();
  }
});
</script>

<style lang="less" scoped>
/* 优化小高度显示 */
:deep(.g2-axis-label) {
  padding-bottom: 8px; /* 增加标签与轴的间距 */
}
</style>